package NetStorage;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Created with IntelliJ IDEA.
 * User: Ratuil
 * Date: 19.03.13
 * Time: 12:26
 * To change this template use File | Settings | File Templates.
 */
public class NetStrorageServerThread implements Runnable{

    private static final int VALUE_LENGHT=10;
    private static final int KEY_RANGE=100;
    InputStream i;
    OutputStream o;


    public NetStrorageServerThread(InputStream i,OutputStream o){
        this.i=i;
        this.o=o;
    }

    public NetStrorageServerThread(){super();}

    /*public static void main(String[] args) {
        new NetStrorageServerThread().run();
    }*/

    @Override
    public void run(){
        ObjectInputStream in=null;
        DataOutputStream out=null;
        try{
            try{
                /*ServerSocket ss=new ServerSocket(6666);
                System.out.println("wait for connection");
                Socket s=ss.accept();
                System.out.println("connection established");
                InputStream i=s.getInputStream();
                OutputStream o=s.getOutputStream();*/

                in=new ObjectInputStream(i);
                out=new DataOutputStream(o);
                while(true){
                    System.out.println("wait for object");
                    Package pac=(Package)in.readObject();
                    System.out.println("object received");
                    if(pac==null){
                        out.writeUTF("NULL DATA RECEIVED");
                        out.flush();
                        return;
                    }
                    if(pac.com==1){
                        NetStrorageServer.storage.put(pac.key,pac.val);
                        out.writeUTF("SUCCESSFULLY ADDED");
                        System.out.println("suc. added");
                    }
                    if(pac.com==0 && NetStrorageServer.storage.containsKey(pac.key)) {
                        out.writeUTF(NetStrorageServer.storage.get(pac.key));
                    }
                    else out.writeUTF("NO SUCH KEY");
                    out.flush();
                }

            }finally{
                //in.close();
                //out.close();
                i.close();
                o.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
